import base64
from rsa import core, PublicKey, transform


class DecryptByPublicKey:
    """
    先产生模数因子
    然后生成rsa公钥
    再使用rsa公钥去解密传入的加密str
    """

    def __init__(self, encrypt_text, pub_key):
        self._encrypt_text = encrypt_text
        self._pub_string_key = pub_key
        # 使用公钥字符串求出模数和因子
        self._modulus = None  # 模数
        self._exponent = None  # 因子
        # 使用PublicKey(模数,因子)算出公钥
        self._pub_rsa_key = None

    def _gen_modulus_exponent(self, s):
        # 对字符串解码, 解码成功返回 模数和指数
        b_str = base64.b64decode(s)
        if len(b_str) < 162:
            return False
        hex_str = b_str.hex()
        # 找到模数和指数的开头结束位置
        m_start = 29 * 2
        e_start = 159 * 2
        m_len = 128 * 2
        e_len = 3 * 2
        self._modulus = int(hex_str[m_start:m_start + m_len], 16)
        self._exponent = int(hex_str[e_start:e_start + e_len], 16)

    def _gen_rsa_pubkey(self):
        # 将pub key string 转换为 pub rsa key
        try:
            rsa_pubkey = PublicKey(self._modulus, self._exponent)
            self._pub_rsa_key = rsa_pubkey.save_pkcs1()
        except Exception as e:
            raise e

    def decode(self):
        """
        decrypt msg by public key
        """
        try:
            public_key = PublicKey.load_pkcs1(self._pub_rsa_key)
            # 确保加密文本是正确的Base64格式
            while len(self._encrypt_text) % 4 != 0:
                self._encrypt_text += '='
            b64decoded_encrypt_text = base64.b64decode(self._encrypt_text)
            length = len(b64decoded_encrypt_text)
            length_max = 128
            decryptDataText = []
            data = b''
            if length >= 128:
                for i in range(0, length, length_max):
                    encrypted = transform.bytes2int(b64decoded_encrypt_text[i:i + length_max])
                    decrypted = core.decrypt_int(encrypted, public_key.e, public_key.n)
                    decrypted_bytes = transform.int2bytes(decrypted)
                    data += decrypted_bytes[decrypted_bytes.find(b'\x00') + 1:]
                try:
                    decryptDataText.append(data.decode())
                except Exception as e:
                    raise e
            else:
                encrypted = transform.bytes2int(b64decoded_encrypt_text)
                decrypted = core.decrypt_int(encrypted, public_key.e, public_key.n)
                decrypted_bytes = transform.int2bytes(decrypted)
                try:
                    decryptDataText.append(decrypted_bytes[decrypted_bytes.find(b'\x00') + 1:].decode())
                except Exception as e:
                    raise e
            if decryptDataText:
                return "".join(decryptDataText)
            else:
                return 'null'
        except Exception as ex:
            return None

    def decrypt(self):
        """
        先产生模数因子
        然后生成rsa公钥
        再使用rsa公钥去解密
        """
        self._gen_modulus_exponent(self._pub_string_key)
        self._gen_rsa_pubkey()
        ret = self.decode()
        return ret


if __name__ == "__main__":
    pub_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJ9s1qlOyv9qpuaTqauW6fUftzE50rVk3yVPZwv1aO1Ch/XSEz76xCwkyvqpaqceRXrPpdBmO5+ruJ+I8osOHo7L5GWEOcMOO+8izp9hXKBBrmRMD4Egpn00k9DhVIEKp/vyddZPS/doxB8onhN6poTJDLdFLFVEicMf52caN9GQIDAQAB'
    encrypt_text = 'aBXw8Zx0ad15EPK668ahUndwi512fYQVbtRixMzeMvJCe8uvLSdohAWYoNxzYkEULDeNP30VaR3cYnRCWJ/v6rMEptW/7udAyqjWBKBUuDoZ6sGGz0HgJgUHhivl80CrqZoExbVOWpICazHNepTc+aaLPisIrRZ/cb41mGZdYnEwMLtTN5oo9dRccM0hYtv15mYTsHDnaJzdESSFLDjs3soS2PX90CMQ8FhMdltrFL8usBpdaT8AdCiWUaTPqa2PhYY1SWBIJMNK18gFIJ1kPctQdFsnlIUfqfvEn0UHPKAMREFE0lPsmS73EtuW/tk0xLxCacTPkLRn7xOp/lvqCzzM8qR7oqkmTndBfW4beI16rgtG7QX4UPOkZjs8g5RPND0nJeP+hrbMvctrqBN+yf1FnnxnivsKSHjzPjnYI4P9QchZNmJfAaI7ANpsv1TBKXeUcr4ZtP4ZjLHwrRM6rJwVwkDlLaPXUw+tkwnzzaOcFSoQW3RxhjFvhyaSInghL4jQgE4Hx/O/BMrYlo/Q+vCj7kSZ4UjgamLyYxLiZR5c2V7HgcPRP9L0BiTqBXFuE+0lYtORf7FHPy8rRpngbCzhVMJ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UbObYpsa3y8yq60gMXZK9QRFlaib8gROx/H0F5wI1K9+Gvy01nxrsd3rUfxVlV314lVw80sfad+wrZyx+Zro6fYZSHTyTNUzGUKfRpK8gTeutq3wQqiTMJ91j3bNYBekYjuGW4Lx2FKnmApJ2yA/XqJLn+RWNRPITEusYl69Yl9TBgMsChRSYXcCP/rV9oR4kvWcspjxxYgBElJQoZUXqoaYen5dSIEgPTFMdMqY5kt6BDC2lKtfIrN/aahCZApI6SjGmbRB0eh2Hh98mgsKxvJcjuUj0Fi2mTkwbyCpySyX5B8uFpVEcBzIsi6Gy+4zLmU8VpgRlL1wKIZotNu261o7nKclVO78T8PVhvJVJPeEz8PHbb0BbLfr4ZndhvGGCQlyzh6+7FxxdjbDO+j8vbb0/F55aRAB1W4KKII7fx9awzNGcCJhl7d9cf3GtobnRgxK82XCAmk9Oe0RSvYP+rW3LxjOIpjuuYhOJBpXXLtmkCqKZEGgoBhEpu033WqJak+luxWj9JwX1VBU/e4='
    result = DecryptByPublicKey(encrypt_text, pub_key).decrypt()
    print("响应解密后的文本：")
    print(result)
